<template>
  <div class="score-management">
    <div class="header">
      <h2>比赛成绩管理</h2>
      <div class="match-info" v-if="matchInfo">
        <p>比赛时间：{{ formatDate(matchInfo.match_date) }} {{ matchInfo.match_time }}</p>
        <p>比赛地点：{{ matchInfo.venue_name }}</p>
        <p>对阵双方：{{ matchInfo.home_school_name || '未知主场' }} vs {{ matchInfo.away_school_name || '未知客场' }}</p>
        <p>比赛组别：{{ matchInfo.home_grade_level_name || '' }} {{ matchInfo.home_group_code || '' }} vs {{ matchInfo.away_group_code || '' }}</p>
      </div>
      <div class="back-button">
        <el-button type="primary" @click="goBack">返回比赛列表</el-button>
      </div>
    </div>
    
    <!-- 过滤条件 -->
    <div class="filter-section">
      <div class="filter-item">
        <label>轮次:</label>
        <el-radio-group v-model="filters.round_number" @change="fetchScores">
          <el-radio v-for="round in rounds" :key="round" :label="round">第{{round}}轮</el-radio>
          <el-radio :label="''">全部</el-radio>
        </el-radio-group>
      </div>
      
      <div class="filter-item">
        <label>魔方类型:</label>
        <el-radio-group v-model="filters.cube_type_id" @change="fetchScores">
          <el-radio v-for="cubeType in cubeTypes" :key="cubeType.id" :label="cubeType.id">{{cubeType.name}}</el-radio>
          <el-radio :label="''">全部</el-radio>
        </el-radio-group>
      </div>
      
      <el-button type="primary" @click="resetFilters">重置筛选</el-button>
    </div>
    
    <!-- 成绩表格 -->
    <div class="scores-table">
      <el-table 
        :data="scores.filter(row => row.draw_number)" 
        border 
        style="width: 100%" 
        v-loading="loading"
        :default-sort="{prop: 'draw_number', order: 'ascending'}"
      >
        <el-table-column prop="id" label="ID" width="80" v-if="false" />
        <el-table-column prop="draw_number" label="桌号" width="80" sortable>
          <template #default="scope">
            <span v-if="scope.row.draw_number">{{ scope.row.draw_number }}</span>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="player_name" label="选手姓名" />
        <el-table-column prop="school_name" label="学校" />
        <el-table-column prop="cube_type_name" label="魔方类型" v-if="!isMobile" />
        <el-table-column prop="round_number" label="轮次" width="80" v-if="!isMobile" />
        <el-table-column prop="score" label="成绩" width="150">
          <template #default="scope">
            <div class="score-input-container">
              <el-input-number 
                v-model="scope.row.score"
                size="small"
                :precision="3" 
                :step="0.001" 
                :min="0"
                :max="998.999"
                controls-position="right"
                placeholder="输入成绩"
                @blur="updateScore(scope.row)"
                :style="isMobile ? 'width: 90px;' : 'width: 100px;'"
                :disabled="isDNF(scope.row.score)"
              />
              <el-button 
                size="small" 
                :type="isDNF(scope.row.score) ? 'danger' : 'default'" 
                @click="toggleDNF(scope.row)"
                style="margin-left: 5px;"
              >
                {{ isDNF(scope.row.score) ? 'DNF' : 'DNF' }}
              </el-button>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="is_confirmed" label="确认" width="80">
          <template #default="scope">
            <el-switch 
              v-model="scope.row.is_confirmed" 
              @change="updateScore(scope.row)"
              :active-value="1"
              :inactive-value="0"
            />
          </template>
        </el-table-column>
      </el-table>
    </div>
    
    <!-- 添加新成绩按钮 -->
    <div class="actions">
      <el-button type="primary" @click="showAddDialog">添加成绩</el-button>
    </div>
    
    <!-- 添加/编辑成绩对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEditing ? '编辑成绩' : '添加成绩'"
      :width="isMobile ? '90%' : '500px'"
    >
      <el-form :model="scoreForm" :label-width="isMobile ? '80px' : '100px'">
        <el-form-item label="选手" v-if="!isEditing">
          <el-select v-model="scoreForm.player_id" placeholder="选择选手" style="width: 100%">
            <el-option
              v-for="player in players"
              :key="player.id"
              :label="`${player.name} (${player.school_name})`"
              :value="player.id"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="魔方类型" v-if="!isEditing">
          <el-select v-model="scoreForm.cube_type_id" placeholder="选择魔方类型" style="width: 100%">
            <el-option
              v-for="cubeType in allCubeTypes"
              :key="cubeType.id"
              :label="cubeType.name"
              :value="cubeType.id"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="轮次" v-if="!isEditing">
          <el-input-number v-model="scoreForm.round_number" :min="1" :max="5" style="width: 100%" />
        </el-form-item>
        
        <el-form-item label="成绩(秒)">
          <div class="score-form-input">
            <el-input-number 
              v-model="scoreForm.score" 
              :precision="3" 
              :step="0.001" 
              :min="0" 
              :max="998.999"
              style="flex: 1; max-width: 140px;"
              :disabled="isDNF(scoreForm.score)"
            />
            <el-button 
              size="default" 
              :type="isDNF(scoreForm.score) ? 'danger' : 'default'" 
              @click="formToggleDNF"
              style="margin-left: 10px;"
            >
              {{ isDNF(scoreForm.score) ? 'DNF' : 'DNF' }}
            </el-button>
          </div>
        </el-form-item>
        
        <el-form-item label="是否确认">
          <el-switch v-model="scoreForm.is_confirmed" />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveScore">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed, onUnmounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'

// 确保axios有正确的baseURL配置
axios.defaults.baseURL = 'http://localhost:3000'

const route = useRoute()
const router = useRouter()
const matchId = computed(() => route.params.id)

// 状态变量
const matchInfo = ref(null)
const rounds = ref([1, 2, 3]) // 默认有3轮
const cubeTypes = ref([])
const allCubeTypes = ref([])
const players = ref([])
const scores = ref([])
const loading = ref(false)
const dialogVisible = ref(false)
const isEditing = ref(false)

// 响应式布局相关
const windowWidth = ref(window.innerWidth)
const isMobile = computed(() => windowWidth.value < 768)
const isDesktop = computed(() => !isMobile.value)

// 监听窗口大小变化
onMounted(() => {
  window.addEventListener('resize', handleResize)
})

// 在组件销毁时移除事件监听器
onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
})

// 处理窗口大小变化
const handleResize = () => {
  windowWidth.value = window.innerWidth
  console.log('窗口尺寸更新:', windowWidth.value, '是否移动端:', isMobile.value)
}

// 筛选条件
const filters = reactive({
  round_number: '',
  cube_type_id: ''
})

// 表单数据
const scoreForm = reactive({
  id: null,
  match_id: computed(() => matchId.value),
  player_id: '',
  cube_type_id: '',
  round_number: 1,
  score: null,
  is_confirmed: false
})

// 返回比赛列表
const goBack = () => {
  router.push('/admin/score')
}

// 获取比赛详情
const fetchMatchInfo = async () => {
  try {
    console.log('获取比赛信息，ID:', matchId.value)
    const response = await axios.get(`/api/matches/${matchId.value}`)
    console.log('获取到的比赛信息:', response.data)
    matchInfo.value = response.data
  } catch (error) {
    console.error('获取比赛信息失败:', error)
    ElMessage.error('获取比赛信息失败')
  }
}

// 初始化
onMounted(async () => {
  try {
    console.log('初始化成绩管理页面，比赛ID:', matchId.value)
    loading.value = true
    await fetchMatchInfo()
    await fetchAllCubeTypes()
    await fetchMatchPlayers()
    // 先获取魔方类型和轮次
    await fetchMatchCubeTypes()
    await fetchMatchRounds()
    // 初始加载所有成绩数据
    await fetchScores()
  } catch (error) {
    console.error('初始化失败:', error)
    ElMessage.error('页面初始化失败')
  } finally {
    loading.value = false
  }
})

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '-'
  const date = new Date(dateString)
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
}

// 获取所有魔方类型
const fetchAllCubeTypes = async () => {
  try {
    const response = await axios.get('/api/cube-types')
    console.log('获取到的所有魔方类型:', response.data)
    allCubeTypes.value = response.data
  } catch (error) {
    console.error('获取魔方类型失败:', error)
    ElMessage.error('获取魔方类型失败')
  }
}

// 获取特定比赛的魔方类型
const fetchMatchCubeTypes = async () => {
  try {
    // 修改API调用，确保路径是正确的
    const response = await axios.get(`/api/matches/${matchId.value}/scores/cube-types`)
    console.log('获取到的魔方类型数据:', response.data)
    if (response.data && response.data.length > 0) {
      cubeTypes.value = response.data
    } else if (allCubeTypes.value.length > 0) {
      // 如果没有特定比赛的魔方类型，使用所有魔方类型
      cubeTypes.value = allCubeTypes.value
    }
  } catch (error) {
    console.error('获取比赛魔方类型失败:', error)
    // 使用所有魔方类型作为后备
    if (allCubeTypes.value.length > 0) {
      cubeTypes.value = allCubeTypes.value
    }
  }
}

// 获取特定比赛的轮次
const fetchMatchRounds = async () => {
  try {
    // 修改API调用，确保路径是正确的
    const response = await axios.get(`/api/matches/${matchId.value}/scores/rounds`)
    console.log('获取到的轮次数据:', response.data)
    
    if (response.data && response.data.length > 0) {
      rounds.value = response.data
    } else {
      rounds.value = [1, 2, 3] // 默认有3轮
    }
  } catch (error) {
    console.error('获取比赛轮次失败:', error)
    rounds.value = [1, 2, 3] // 默认有3轮
  }
}

// 获取比赛的选手
const fetchMatchPlayers = async () => {
  try {
    // 参考DrawManagement.vue中的API调用
    const response = await axios.get(`/api/matches/${matchId.value}/players`)
    console.log('获取到的选手数据:', response.data)
    players.value = response.data
  } catch (error) {
    console.error('获取比赛选手失败:', error)
    ElMessage.error('获取比赛选手失败')
  }
}

// 获取成绩列表
const fetchScores = async () => {
  loading.value = true
  
  try {
    console.log('开始获取成绩列表，筛选条件:', { ...filters, match_id: matchId.value })
    // 构建查询参数
    const params = {
      match_id: matchId.value
    }
    if (filters.round_number) params.round_number = filters.round_number
    if (filters.cube_type_id) params.cube_type_id = filters.cube_type_id
    
    const response = await axios.get('/api/scores', { params })
    console.log('获取到的成绩数据:', response.data)
    scores.value = response.data
  } catch (error) {
    console.error('获取成绩列表失败:', error)
    // 显示更详细的错误信息
    if (error.response?.data?.error) {
      ElMessage.error(`获取成绩列表失败: ${error.response.data.error}`)
    } else {
      ElMessage.error('获取成绩列表失败')
    }
  } finally {
    loading.value = false
  }
}

// 重置筛选条件
const resetFilters = () => {
  filters.round_number = ''
  filters.cube_type_id = ''
  fetchScores()
}

// 显示添加对话框
const showAddDialog = async () => {
  isEditing.value = false
  
  // 重置表单
  scoreForm.id = null
  scoreForm.player_id = ''
  scoreForm.cube_type_id = filters.cube_type_id || ''
  scoreForm.round_number = filters.round_number || 1
  scoreForm.score = null
  scoreForm.is_confirmed = false
  
  dialogVisible.value = true
}

// 编辑成绩
const editScore = (row) => {
  isEditing.value = true
  
  // 填充表单
  scoreForm.id = row.id
  scoreForm.score = row.score
  scoreForm.is_confirmed = row.is_confirmed === 1
  
  dialogVisible.value = true
}

// 检查是否为DNF成绩
const isDNF = (score) => {
  return score === 999 || score > 998.999;
}

// 更新成绩
const updateScore = async (row) => {
  try {
    console.log('更新成绩:', row)
    
    // 检查成绩是否在合理范围内
    if (row.score !== null && !isDNF(row.score) && (row.score > 998.999 || row.score < 0)) {
      ElMessage.warning('成绩数值必须在0-998.999之间，请检查输入');
      await fetchScores(); // 重新获取数据，还原错误输入
      return;
    }
    
    // 防止数值精度问题
    let scoreValue = row.score;
    if (scoreValue !== null && !isDNF(scoreValue)) {
      // 将数值限制在3位小数
      scoreValue = Math.round(scoreValue * 1000) / 1000;
    }
    
    const response = await axios.put(`/api/scores/${row.id}`, {
      score: scoreValue,
      is_confirmed: row.is_confirmed ? 1 : 0
    })
    
    console.log('成绩更新结果:', response.data)
    ElMessage.success('成绩更新成功')
  } catch (error) {
    console.error('更新成绩失败:', error)
    
    // 详细记录错误信息
    if (error.response) {
      console.error('错误响应数据:', error.response.data);
      console.error('错误状态码:', error.response.status);
    } else {
      console.error('完整错误对象:', JSON.stringify(error));
    }
    
    // 显示更详细的错误信息
    if (error.response?.data?.error) {
      ElMessage.error(`更新成绩失败: ${error.response.data.error}`)
    } else {
      ElMessage.error(`更新成绩失败(${error.message})，请联系管理员检查服务器日志`)
    }
    
    // 错误后重新获取数据
    await fetchScores();
  }
}

// 切换DNF状态
const toggleDNF = (row) => {
  if (isDNF(row.score)) {
    // 从DNF恢复到默认值
    row.score = 0;
  } else {
    // 标记为DNF
    row.score = 999;
  }
  updateScore(row);
}

// 表单中切换DNF状态
const formToggleDNF = () => {
  if (isDNF(scoreForm.score)) {
    // 从DNF恢复到默认值
    scoreForm.score = 0;
  } else {
    // 标记为DNF
    scoreForm.score = 999;
  }
}

// 保存成绩
const saveScore = async () => {
  try {
    console.log('保存成绩:', scoreForm)
    
    if (isEditing.value) {
      // 更新现有成绩
      const response = await axios.put(`/api/scores/${scoreForm.id}`, {
        score: scoreForm.score,
        is_confirmed: scoreForm.is_confirmed ? 1 : 0
      })
      
      console.log('成绩更新结果:', response.data)
      ElMessage.success('成绩更新成功')
    } else {
      // 创建新成绩
      if (!scoreForm.player_id || !scoreForm.cube_type_id || !scoreForm.round_number) {
        return ElMessage.warning('请填写所有必要信息')
      }
      
      const response = await axios.post('/api/scores', {
        match_id: matchId.value,
        player_id: scoreForm.player_id,
        cube_type_id: scoreForm.cube_type_id,
        round_number: scoreForm.round_number,
        score: scoreForm.score,
        is_confirmed: scoreForm.is_confirmed ? 1 : 0
      })
      
      console.log('成绩添加结果:', response.data)
      ElMessage.success('成绩添加成功')
    }
    
    // 关闭对话框并刷新数据
    dialogVisible.value = false
    await fetchScores()
  } catch (error) {
    console.error('保存成绩失败:', error)
    
    // 显示更详细的错误信息
    if (error.response?.data?.error) {
      ElMessage.error(`保存成绩失败: ${error.response.data.error}`)
    } else {
      ElMessage.error('保存成绩失败，请重试')
    }
  }
}

// 删除成绩
const deleteScore = async (row) => {
  try {
    console.log('准备删除成绩:', row)
    await ElMessageBox.confirm('确定要删除这条成绩记录吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const response = await axios.delete(`/api/scores/${row.id}`)
    console.log('成绩删除结果:', response.data)
    
    ElMessage.success('成绩删除成功')
    await fetchScores()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除成绩失败:', error)
      
      // 显示更详细的错误信息
      if (error.response?.data?.error) {
        ElMessage.error(`删除成绩失败: ${error.response.data.error}`)
      } else {
        ElMessage.error('删除成绩失败，请重试')
      }
    }
  }
}
</script>

<style scoped>
.score-management {
  padding: 20px;
}

.header {
  margin-bottom: 20px;
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.match-info {
  background-color: #f5f7fa;
  border-radius: 5px;
  padding: 15px;
  margin-bottom: 15px;
}

.match-info p {
  margin: 5px 0;
}

.back-button {
  margin-bottom: 15px;
}

.filter-section {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.filter-item {
  display: flex;
  align-items: center;
  gap: 10px;
}

@media screen and (max-width: 768px) {
  .filter-section {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .filter-item {
    width: 100%;
    flex-direction: column;
    align-items: flex-start;
  }
  
  .score-management {
    padding: 10px;
  }
  
  .match-info {
    padding: 10px;
    font-size: 14px;
  }
  
  .el-radio-group {
    display: flex;
    flex-wrap: wrap;
    gap: 5px;
  }
}

.scores-table {
  margin-bottom: 20px;
}

.actions {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.score-input-container {
  display: flex;
  align-items: center;
}

.score-form-input {
  display: flex;
  align-items: center;
}

/* 手机端隐藏特定列 */
@media screen and (max-width: 768px) {
  .hidden-mobile {
    display: none;
  }
}
</style>

<style>
.score-input-container {
  display: flex;
  align-items: center;
}

/* 全局应用的媒体查询样式 */
@media screen and (max-width: 768px) {
  .el-form-item__label {
    font-size: 14px;
  }
  
  .el-button--small {
    padding: 8px 10px;
  }
  
  .el-input-number {
    width: 90px;
  }
  
  .el-dialog__header {
    padding: 15px;
  }
  
  .el-dialog__body {
    padding: 15px;
  }
  
  .el-dialog__footer {
    padding: 10px 15px;
  }
}
</style> 